import React, { useState, useEffect } from 'react'
import { Input, Tabs, Typography, List, Avatar, Button, Message } from '@arco-design/web-react'
import { IconEdit, IconDelete, IconPlus, IconLoading } from '@arco-design/web-react/icon'
import { searchUserListApi, searchGroupListApi, addFriendApi, joinGroupApi } from '@@/src/api/chat'
import { useSelector } from 'react-redux'

const TabPane = Tabs.TabPane
const InputSearch = Input.Search

const style = {
  textAlign: 'center',
  marginTop: 20,
}

function Search(props) {
  const userStore = useSelector((state) => state.user)
  const { id: currentUser } = userStore.info
  const [userList, setUserList] = useState([])
  const [groupList, setGroupList] = useState([])
  const [loading, setLoading] = useState(false)
  const [searchKey, setSearchKey] = useState('')

  // 添加朋友
  const handleAddFriend = (userId) => {
    addFriendApi({ userId: currentUser, friendId: userId, status: 0 })
      .then((res) => {
        console.log(res)
        if (res.data) {
          Message.success('已发送好友申请')
          fetchUserData()
        } else {
          Message.error('发送好友申请异常')
        }
      })
      .catch((err) => {
        Message.error('发送好友申请异常')
      })
  }

  // 加入群聊
  const handleJoinGroup = (groupId) => {
    joinGroupApi({ userId: currentUser, groupId: groupId })
      .then((res) => {
        console.log(res)
        if (res.data) {
          Message.success('已加入群聊')
          fetchGroupData()
          props.refreshList()
        } else {
          Message.error('加入群聊异常')
        }
      })
      .catch((err) => {
        Message.error('加入群聊异常')
      })
  }

  // 搜索
  const handleSearch = async () => {
    // 没加载到用户数据
    if (currentUser === -1 || searchKey === '') {
      return
    }
    setLoading((prev) => true)
    await fetchUserData()
    await fetchGroupData()
    setLoading(false)
  }

  // 请求接口
  // 1.用户列表
  const getUserList = async () => {
    let result = await searchUserListApi({
      userId: currentUser,
      searchKey: searchKey,
      isFriend: false,
      limit: 5,
    })
    return result?.data || []
  }
  // 2.群组列表
  const getGroupList = async () => {
    let result = await searchGroupListApi({
      userId: currentUser,
      searchKey: searchKey,
      isFriend: false,
      limit: 5,
    })
    return result?.data || []
  }

  const fetchUserData = async () => {
    const result1 = await getUserList()
    setUserList(result1)
  }
  const fetchGroupData = async () => {
    const result2 = await getGroupList()
    setGroupList(result2)
  }

  const renderUserActions = (userId, status) => {
    if (status === 1) {
      return (
        <Button size='default' type='secondary' disabled status='success'>
          已是好友
        </Button>
      )
    } else if (status === 0) {
      return (
        <Button size='default' type='secondary' disabled>
          已发送申请
        </Button>
      )
    } else {
      return (
        <Button size='default' type='primary' onClick={() => handleAddFriend(userId)}>
          添加好友
        </Button>
      )
    }
  }

  const renderGroupActions = (groupId, status) => {
    if (status === 1) {
      return (
        <Button size='default' type='secondary' disabled status='success'>
          已加入
        </Button>
      )
    } else {
      return (
        <Button size='default' type='primary' onClick={() => handleJoinGroup(groupId)}>
          加入群聊
        </Button>
      )
    }
  }

  return (
    <div style={{ width: '100%', height: '100%' }}>
      {/* 搜索框 */}
      <div
        style={{
          height: '25%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-end',
          alignItems: 'center',
        }}
      >
        <Typography.Title heading={3}>查找用户和群组</Typography.Title>
        <InputSearch
          size='large'
          allowClear
          searchButton
          loading={loading}
          value={searchKey}
          placeholder='请输入用户姓名、邮箱或手机号，或群组名称'
          style={{ width: '50%', marginTop: 20, marginBottom: 10 }}
          onChange={(input) => setSearchKey(input)}
          onPressEnter={() => handleSearch()}
        />
      </div>
      {/* 搜索结果 */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Tabs type={'rounded'} style={{ width: '50%' }}>
          <TabPane key='1' title='用户'>
            <List
              bordered={false}
              // split={true}
              loading={loading}
              size={'small'}
              scrollLoading={true}
              pagination={{ pageSize: 5, total: userList.length }}
              dataSource={userList}
              render={(item, index) => (
                <List.Item key={index} actions={[renderUserActions(item.id, item.status)]}>
                  <List.Item.Meta
                    avatar={
                      <Avatar shape='square'>
                        {item.avatar ? <img alt='avatar' src={item.avatar} /> : item.name.slice(0, 1)}
                      </Avatar>
                    }
                    title={item.name}
                    description={item.description}
                  />
                </List.Item>
              )}
              noDataElement={<div>没有找到哦~</div>}
            />
          </TabPane>
          <TabPane key='2' title='群组'>
            <List
              bordered={false}
              // split={true}
              loading={loading}
              size={'small'}
              scrollLoading={true}
              pagination={{ pageSize: 5, total: groupList.length }}
              dataSource={groupList}
              render={(item, index) => (
                <List.Item key={index} actions={[renderGroupActions(item.id, item.status)]}>
                  <List.Item.Meta
                    avatar={
                      <Avatar shape='square'>
                        {item.avatar ? <img alt='avatar' src={item.avatar} /> : item.name.slice(0, 1)}
                      </Avatar>
                    }
                    title={item.name}
                    description={item.description}
                  />
                </List.Item>
              )}
              noDataElement={<div>没有找到哦~</div>}
            />
          </TabPane>
        </Tabs>
      </div>
    </div>
  )
}

export default Search
